#include "historytable.h"
#include <QScrollBar>
#include <QDateTime>

#include <QDebug>

HistoryTable::HistoryTable(const QString &title, const QStringList &headers, const QList<int> &colWidths,bool enableInputFields, bool enableButtons, QWidget *parent)
    : QWidget(parent), tableTitle(title), tableHeaders(headers), columnWidths(colWidths),inputFieldsEnabled(enableInputFields), buttonsEnabled(enableButtons)
{
    initializeUI();
}

void HistoryTable::initializeUI()
{
    // 初始化布局
    initializeLayouts();

    // 初始化表格
    initializeTable();

    // 初始化输入框（如果启用）
    if (inputFieldsEnabled)
    {
        initializeInputFields();
    }

    // 初始化按钮（如果启用）
    if (buttonsEnabled)
    {
        initializeButtons();
    }
}

void HistoryTable::initializeTable()
{
    tableWidget = new QTableWidget(this);
    tableWidget->setColumnCount(tableHeaders.size()); // 根据表头数量设置列数
    tableWidget->setHorizontalHeaderLabels(tableHeaders); // 设置表头
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); // 禁止编辑

    // 设置表格样式
    QString tableStyle = R"(
        QTableWidget {
            background-color: white;
            border: 1px solid #ddd;
            font-family: "Segoe UI", sans-serif;
            font-size: 14px;
        }
        QTableWidget::item {
            padding: 8px;
            border-bottom: 1px solid #ddd;
        }
        QTableWidget::item:selected {
            background-color: #0078d7;
            color: white;
        }
        QHeaderView::section {
            background-color: #f5f5f5;
            color: #333;
            padding: 8px;
            border: none;
            font-weight: bold;
            font-size: 14px;
        }
        QTableWidget::item:hover {
            background-color: #f0f0f0;
        }
    )";
    tableWidget->setStyleSheet(tableStyle);

    // 设置交替行颜色
    tableWidget->setAlternatingRowColors(true);
    tableWidget->setStyleSheet("alternate-background-color: #f9f9f9;");

    // 设置表头
    tableWidget->verticalHeader()->setVisible(false);
    tableWidget->verticalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);

    // 设置单击选择一行
    tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);

    // 设置列宽
     if (!columnWidths.isEmpty() && columnWidths.size() == tableWidget->columnCount())
     {
         for (int col = 0; col < columnWidths.size(); ++col)
         {
             if(columnWidths[col] != 0)
             {
                tableWidget->setColumnWidth(col, columnWidths[col]); // 设置每列宽度
                if(columnWidths.size() - 1 == col)
                {
                   tableWidget->horizontalHeader()->setSectionResizeMode(col,QHeaderView::Stretch);
                }
             }
             else
             {
                 tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); // 列宽自适应
                 tableWidget->verticalHeader()->setDefaultSectionSize(36); // 设置默认行高
             }
         }
     }
     else
     {
         // 默认列宽
         qDebug()<<"JJJ"<<columnWidths;
         tableWidget->setColumnWidth(0, 80); // 序号列
         tableWidget->setColumnWidth(1, 150); // 时间列
         tableWidget->setColumnWidth(2, 300); // 事件列
         tableWidget->horizontalHeader()->setSectionResizeMode(3,QHeaderView::Stretch);
     }

    // 设置表头字体
    QFont headerFont = tableWidget->horizontalHeader()->font();
    headerFont.setBold(true);
    headerFont.setFamily("Segoe UI");
    tableWidget->horizontalHeader()->setFont(headerFont);

    // 设置滚动条样式
    QString scrollBarStyle = R"(
        QScrollBar:vertical {
            background: #f5f5f5;
            width: 10px;
            margin: 0px 0px 0px 0px;
        }
        QScrollBar::handle:vertical {
            background: #ccc;
            min-height: 20px;
            border-radius: 4px;
        }
        QScrollBar::add-line:vertical,
        QScrollBar::sub-line:vertical {
            background: none;
        }
        QScrollBar::add-page:vertical,
        QScrollBar::sub-page:vertical {
            background: none;
        }
    )";
    tableWidget->verticalScrollBar()->setStyleSheet(scrollBarStyle);
    tableWidget->horizontalScrollBar()->setStyleSheet(scrollBarStyle);

    // 添加标题
    titleLabel = new QLabel(tableTitle, this);
    titleLabel->setAlignment(Qt::AlignCenter); // 设置标题居中显示
    titleLabel->setStyleSheet("font-size: 18px; font-weight: bold; color: #333; margin-bottom: 10px;");
    mainLayout->addWidget(titleLabel);
    mainLayout->addWidget(tableWidget); // 将表格添加到布局
}

void HistoryTable::initializeInputFields()
{
    eventNameLineEdit = new QLineEdit(this);
    eventNameLineEdit->setPlaceholderText("Enter event name");

    eventDateLineEdit = new QLineEdit(this);
    eventDateLineEdit->setPlaceholderText("Enter event date (e.g., YYYY-MM-DD)");

    inputLayout->addWidget(eventNameLineEdit);
    inputLayout->addWidget(eventDateLineEdit);

    // 将输入框布局添加到主布局
    mainLayout->addLayout(inputLayout);
}

void HistoryTable::initializeButtons()
{
    addEventButton = new QPushButton("Add Event", this);
    saveButton = new QPushButton("Save", this);
    loadButton = new QPushButton("Load", this);

    // 连接按钮点击事件到槽函数
    connect(addEventButton, &QPushButton::clicked, this, &HistoryTable::onAddEventButtonClicked);
    connect(saveButton, &QPushButton::clicked, this, &HistoryTable::onSaveButtonClicked);
    connect(loadButton, &QPushButton::clicked, this, &HistoryTable::onLoadButtonClicked);

    buttonLayout->addWidget(addEventButton);
    buttonLayout->addWidget(saveButton);
    buttonLayout->addWidget(loadButton);

    // 将按钮布局添加到主布局
    mainLayout->addLayout(buttonLayout);
}

void HistoryTable::initializeLayouts()
{
    // 主布局
    mainLayout = new QVBoxLayout(this);

    // 输入框布局
    inputLayout = new QHBoxLayout();

    // 按钮布局
    buttonLayout = new QHBoxLayout();
}


void HistoryTable::addEvent(int index, const QString &time, const QString &event, int status)
{
    // 查找所有相同事件ID的事件行
    QList<int> existingRows;
    for (int row = 0; row < tableData.size(); ++row)
    {
        if (tableData[row][0] == QString::number(index))
        {
            existingRows.append(row);
        }
    }

    // 如果存在相同事件ID的事件行
    if (!existingRows.isEmpty())
    {
        // 将所有相同事件ID的事件行的字体颜色设置为黑色（已确认）
        for (int row : existingRows)
        {
            for (int col = 0; col < tableWidget->columnCount(); ++col)
            {
                QTableWidgetItem *item = tableWidget->item(row, col);
                if (item)
                {
                    item->setForeground(Qt::black); // 设置字体颜色为黑色
                }
            }
        }
    }

    // 添加新事件到动态多维数组
    QVector<QString> newRow;
    newRow << QString::number(index) // 事件ID（不显示在表格中）
           << QString::number(tableData.size() + 1) // 递增序号
           << time
           << event
           << QString::number(status); // 状态
    tableData.append(newRow);

    // 添加新事件到 QTableWidget
    int row = tableWidget->rowCount();
    tableWidget->insertRow(row);

    // 添加递增序号
    QTableWidgetItem *seqItem = new QTableWidgetItem(QString::number(tableData.size()));
    tableWidget->setItem(row, 0, seqItem);

    // 添加时间
    QTableWidgetItem *timeItem = new QTableWidgetItem(time);
    tableWidget->setItem(row, 1, timeItem);

    // 添加事件
    QTableWidgetItem *eventItem = new QTableWidgetItem(event);
    tableWidget->setItem(row, 2, eventItem);

    // 添加状态
    QTableWidgetItem *statusItem = new QTableWidgetItem(QString::number(status));
    tableWidget->setItem(row, 3, statusItem);

    // 根据状态值设置字体颜色
    switch (status)
    {
        case 0: // 黑色（已确认）
            for (int col = 0; col < tableWidget->columnCount(); ++col)
            {
                QTableWidgetItem *item = tableWidget->item(row, col);
                if (item)
                {
                    item->setForeground(Qt::black); // 设置字体颜色为黑色
                }
            }
            break;

        case 1: // 红色（报警）
            for (int col = 0; col < tableWidget->columnCount(); ++col)
            {
                QTableWidgetItem *item = tableWidget->item(row, col);
                if (item)
                {
                    item->setForeground(Qt::red); // 设置字体颜色为红色
                }
            }
            break;

        case 2: // 绿色（报警恢复）
            for (int col = 0; col < tableWidget->columnCount(); ++col)
            {
                QTableWidgetItem *item = tableWidget->item(row, col);
                if (item)
                {
                    item->setForeground(Qt::blue); // 设置字体颜色为绿色
                }
            }
            break;
    }

    // 触发信号
    emit eventAdded(index, time, event, status);

    // 强制刷新表格
    tableWidget->viewport()->update();
}





int HistoryTable::findRowByIndex(int index)
{
    for (int row = 0; row < tableWidget->rowCount(); ++row)
    {
        if (tableWidget->item(row, 0)->text().toInt() == index)
        {
            return row;
        }
    }
    return -1; // 未找到
}

bool HistoryTable::saveToFile(const QString &filePath)
{
    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream out(&file);
        for (int i = 0; i < tableWidget->rowCount(); ++i)
        {
            QString index = tableWidget->item(i, 0)->text();
            QString time = tableWidget->item(i, 1)->text();
            QString event = tableWidget->item(i, 2)->text();
            QString status = tableWidget->item(i, 3)->text();
            out << index << "," << time << "," << event << "," << status << "\n";
        }
        file.close();
        showMessage("Success", "Data saved successfully!");
        return true;
    }
    else
    {
        showMessage("Error", "Failed to save data!");
        return false;
    }
}

bool HistoryTable::loadFromFile(const QString &filePath)
{
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&file);
        tableWidget->setRowCount(0); // 清空表格
        while (!in.atEnd())
        {
            QString line = in.readLine();
            QStringList parts = line.split(",");
            if (parts.size() == 4)
            {
                int index = parts[0].toInt();
                QString time = parts[1];
                QString event = parts[2];
                int status = parts[3].toInt();
                addEvent(index, time, event, status);
            }
        }
        file.close();
        showMessage("Success", "Data loaded successfully!");
        return true;
    }
    else
    {
        showMessage("Error", "Failed to load data!");
        return false;
    }
}

void HistoryTable::clearTable()
{
    tableWidget->setRowCount(0);
}

void HistoryTable::setTitle(const QString &title)
{
    tableTitle = title;
    if (titleLabel) {
        titleLabel->setText(tableTitle);
    }
}

void HistoryTable::setHeaders(const QStringList &headers)
{
    tableHeaders = headers;
    tableWidget->setColumnCount(tableHeaders.size());
    tableWidget->setHorizontalHeaderLabels(tableHeaders);
}

void HistoryTable::setInputFieldsEnabled(bool enabled)
{
    inputFieldsEnabled = enabled;
    if (eventNameLineEdit && eventDateLineEdit)
    {
        eventNameLineEdit->setVisible(enabled);
        eventDateLineEdit->setVisible(enabled);
    }
}

void HistoryTable::setButtonsEnabled(bool enabled)
{
    buttonsEnabled = enabled;
    if (addEventButton && saveButton && loadButton)
    {
        addEventButton->setVisible(enabled);
        saveButton->setVisible(enabled);
        loadButton->setVisible(enabled);
    }
}

void HistoryTable::onAddEventButtonClicked()
{
    QString eventName = eventNameLineEdit->text();
    QString eventDate = eventDateLineEdit->text();

    if (!eventName.isEmpty() && !eventDate.isEmpty())
    {
        int index = tableWidget->rowCount() + 1; // 自动生成索引号
        QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz");
        int status = 0; // 默认状态为 0（已确认）
        addEvent(index, time, eventName, status);
        eventNameLineEdit->clear();
        eventDateLineEdit->clear();
    }
    else
    {
        showMessage("Error", "Event name and date cannot be empty!");
    }
}

void HistoryTable::onSaveButtonClicked()
{
    saveToFile("history.txt");
}

void HistoryTable::onLoadButtonClicked()
{
    loadFromFile("history.txt");
}

void HistoryTable::showMessage(const QString &title, const QString &message)
{
    QMessageBox::information(this, title, message);
}
